<template>
  <el-dialog
    class="public-dialog"
    :title="`${isEdit ? '修改' : '新增'}物流商API信息`"
    width="936"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
  >
    <div class="h-[460px]">
      <VForm
        ref="form"
        :model="model"
        :fieldList="fieldList"
        :options="formOption"
        :rules="rules"
        :disabled="disabled"
      >
      </VForm>
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? '关闭' : '取消' }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from 'element-plus'
import VForm from '@/components/Form/index.vue'

import {
  createLogisticsApi,
  updateLogisticsApi,
  logisticsApiDetail,
} from '../api'

const props = defineProps({
  id: { type: [String, Number], default: '' },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
})

const emit = defineEmits(['update:modelValue', 'refresh', 'close'])

const formOption = {
  inline: true,
  labelPosition: 'top',
}

const rules = {
  api_name: [
    { required: true, message: '请输入物流商API名称', trigger: 'blur' },
  ],
  api_ident: [
    { required: true, message: '请输入物流商API标识', trigger: 'blur' },
  ],
  api_config: [{ required: true, message: '请输入API配置项', trigger: 'blur' }],
}

const form = ref()
const model = ref({})
const loading = ref()

const publicStyle = { style: { width: '240px' } }
const fieldList = [
  {
    field: 'api_name',
    label: '物流商API名称',
    ...publicStyle,
  },
  {
    field: 'api_ident',
    label: '物流商API标识',
    ...publicStyle,
  },
  {
    field: 'api_config',
    label: 'API配置项',
    type: 'textarea',
    placeholder: '换行并以英文逗号和分号隔开',
    autosize: { minRows: 4, maxRows: 8 },
    full: true,
    itemStyle: { width: '100%' },
  },
  {
    field: 'api_config_track',
    label: 'API轨迹配置项',
    type: 'textarea',
    placeholder: '换行并以英文逗号和分号隔开',
    autosize: { minRows: 4, maxRows: 8 },
    full: true,
    itemStyle: { width: '100%' },
  },
  {
    field: 'api_cargo_status',
    label: '物流商轨迹状态',
    type: 'textarea',
    placeholder: '换行并以英文逗号和分号隔开',
    autosize: { minRows: 4, maxRows: 8 },
    full: true,
    itemStyle: { width: '100%' },
  },
  {
    field: 'remark',
    label: '备注',
    type: 'textarea',
    autosize: { minRows: 4, maxRows: 8 },
    full: true,
    itemStyle: { width: '100%' },
  },
]

watch(
  () => props.id,
  val => {
    if (val) {
      if (!props.modelValue) return
      nextTick(() => {
        getDetail(val)
      })
    }
  }
)

const getDetail = async id => {
  try {
    const { data } = await logisticsApiDetail({ id })

    const { api_cargo_status, api_config, api_config_track } = data
    model.value = {
      ...data,
    }
  } catch (e) {
    model.value = {}
    console.error(e)
  }
}

const isEdit = computed(() => {
  return !!props.id
})

const conversionConfigStr = value => {
  return JSON.stringify(value)
  if (value?.length === 0) return ''

  try {
    let str = ''
    for (let key in value) {
      str += `${key}:${value[key]}\n`
    }
    console.warn(str)
    return str
  } catch (e) {
    return ''
  }
}

const conversionConfig = value => {
  if (!value) return undefined
  if (!value.trim?.().length) return undefined

  try {
    const _config = value.split('\n').filter(n => !!n)
    if (!_config.length) return undefined
    const _new = _config.reduce((pre, cur) => {
      const _split = cur.split(':')
      return { ...pre, [_split[0]]: _split.splice(1, _split.length).join(':') }
    }, {})
    return _new
  } catch (e) {
    return undefined
  }
}

const handleSave = async () => {
  try {
    const formInfo = await form.value.submit()
    console.warn(formInfo)
    const api = {
      edit: updateLogisticsApi,
      add: createLogisticsApi,
    }
    const { id } = props

    const { api_cargo_status, api_config, api_config_track } = formInfo
    await api[isEdit.value ? 'edit' : 'add']({
      id: id || undefined,
      ...formInfo,
      api_config: api_config,
      api_cargo_status: api_cargo_status,
      api_config_track: api_config_track,
    })
    ElMessage.success(isEdit.value ? '修改成功' : '保存成功')
    handleClose(true)
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning('请检查表单信息')
    }
    console.error(e)
  } finally {
    loading.value = false
  }
}

const handleClose = async refresh => {
  model.value = {}
  await nextTick()
  form.value.resetForm()
  emit('update:modelValue', false)
  emit('close')
  if (refresh) emit('refresh')
}
</script>
